package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import java.util.Arrays;

import static com.shanxia.codec.Decoder.byteToAscii;
import static com.shanxia.codec.Decoder.getUint16;

/**
 * C -> S
 * 充电桩上传用户密码验证报文
 * 充电桩对后台服务器的充电桩整形参数设置报文应答
 */
@Data
public class Cmd206 extends ProtocolDataBase {

    public static final int MIN_SIZE = 148;

    private int v1;
    private int v2;
    private String sn;                              // 充电桩编码
    private String chargingCardNum;                 // 充电卡号
    private String pwd;                             // 用户充电密码
    private String random;                          // 卡扇区数据随机数

    public Cmd206(){
        super.setCmd(206);
    }

    public static Cmd206 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd206 cmd = new Cmd206();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 32字节充电桩编码
        cmd.sn = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 32), true);
        offset += 32;
        // 32字节充电卡号
        cmd.chargingCardNum = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 32), true);
        offset += 32;
        // 32字节用户充电密码
        // 用户选择无密码时，每个字节均为 0xFF
        byte[] pwdArr = Arrays.copyOfRange(dataField, offset, offset + 32);
        boolean legalPwd = false;
        for (byte pwdByte : pwdArr) {
            if (pwdByte != 0xFF) {
                legalPwd = true;
                break;
            }
        }
        cmd.pwd = legalPwd ? byteToAscii(pwdArr, true) : "";
        offset += 32;
        // 48字节卡扇区数据随机数
        cmd.random = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 48), true);
        return cmd;
    }

    @Override
    public String toString() {

        StringBuffer buffer = new StringBuffer();
        buffer.append("#cmd206#").append("\n");
        buffer.append("v1:").append(v1).append("\n");
        buffer.append("v2:").append(v2).append("\n");
        buffer.append("充电桩编码:").append(sn).append("\n");
        buffer.append("充电卡号:").append(chargingCardNum).append("\n");
        buffer.append("用户充电卡密码:").append(pwd).append("\n");
        buffer.append("卡扇区数据随机数:").append(random).append("\n");
        return buffer.toString();
    }
}
